package org.brisling.medical.queryService;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import org.brisling.base.domain.ListDomain;
import org.brisling.base.service.AbstractBaseQueryService;
import org.brisling.common.ConstSysParam;
import org.brisling.common.exception.DangerousOperatorException;
import org.brisling.common.util.DateUtil;
import org.brisling.medical.domain.LogicWrong;
import org.brisling.medical.domain.MedicalRecipel;
import org.brisling.medical.service.RecipelService;
import org.brisling.medical.vo.VOQueryLargeCost;
import org.brisling.sysman.queryService.QueryDictionaryService;
import org.brisling.sysman.queryService.QueryPermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * <p>Title: QueryLogicwrongService</p>
 * <p>Description: 逻辑错误监控查询service</p>
 * <p>Company: tongking</p>
 * @author shura
 * @since 1.0
 * @version 1.0
 * @date 2016年7月20日 下午10:07:08
 */
@RestController
@RequestMapping("/logicWrong/query")
public class QueryLogicwrongService extends AbstractBaseQueryService<LogicWrong>{
	

	@Autowired
	private QueryDictionaryService dicService;
	@Autowired
	private RecipelService qrService;
	
	@Autowired
	private QueryPermissionService qryPermissionService;
	
	public QueryLogicwrongService(){
		this.moduleName = ConstSysParam.MODULE_LOGIC_WRONG;
		this.subSystem = ConstSysParam.SUBSYSTEM_MEDICAL;
		this.tableName = ConstSysParam.VIEW_PREFIX +this.getTableName(LogicWrong.class);
		this.clazz = LogicWrong.class;
	}
	
	@PersistenceContext(unitName=ConstSysParam.SUBSYSTEM_SYSMAN)
	@Autowired
	protected void setEntityManager(EntityManager entityManager){
		this.entityManager = entityManager;		
	}
	
	@RequestMapping("/mainPage.action")
	public ModelAndView getMainPage(){
		return this.getBizMainPage();
	}
	
	/* (non-Javadoc)
	 * @see org.brisling.service.sysman.DepartmentServiceInf#getEditPage()
	 */
	@RequestMapping("/editPage.action")
	public ModelAndView getEditPage(){
		return this.getBizEditPage();
	}
	
	@RequestMapping("/getListDomain.action")
	public ListDomain<LogicWrong> getListDomain(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="condition",required=false) String condition,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(condition!=null){
			String whereCorse=String.format(sb.append("deptid = %1$s").toString(),condition);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedListDomain(page,rows,sql);
	}
	
	@RequestMapping("/getList.action")
	public List<LogicWrong> getList(@RequestParam(value="page",required=false) Integer page,
			@RequestParam(value="rows",required=false) Integer rows,
			@RequestParam(value="deptid",required=false) Integer deptid,
			@RequestParam(value="sort",required=false) String sort){		
		
		StringBuilder sb = new StringBuilder();
		String sql = "";
		if(deptid!=null){
			String whereCorse=String.format(sb.append("\"deptid\" = %1$d").toString(),deptid);
			sql = String.format(this.TW_SQL, this.tableName,whereCorse);
		}else{
			sql = String.format(this.T_SQL, this.tableName);
		}
		
		return super.getPagedList(page,rows,sql);
	}
	
	/**
	 * 根据用户id查找用户信息
	 * @param id	用户id
	 * @return 用户信息记录 
	 */
	@RequestMapping("/getOne.action")
	public LogicWrong getOne(@RequestParam(value="id",required=false) Long id){
		return super.getOne(id);
	}
	
	/**
	 * 根据用户唯一编码查找用户信息
	 * @param identify	用户唯一编码
	 * @return 用户信息记录
	 */
	@RequestMapping("/getOneByIdentify.action")
	public LogicWrong getOneByIdentify(@RequestParam(value="identify",required=false) String identify){	
		return super.getOneByIdentify(identify);
	}
	

	public int autosave (String userId, String time){
		String Logictype[]={"examine_days","bed_days","nursing_days","oxygen_days","grave_days"};
		ArrayList<MedicalRecipel> medicalRec = new ArrayList<MedicalRecipel>();
		for (int i=0;i<4;i++){
			int hhh = 0;
			List <VOQueryLargeCost> lists = this.getLogicCost(Logictype[i], time);//!!!!!!!!!!!!
			if (lists != null){
				for (VOQueryLargeCost e : lists){
					MedicalRecipel tmp = this.logiccostToMedicalRecipel(userId,e,i);//!!!!!!!!!!!!!
					System.out.println(hhh++);
					if(hhh == 150){
						System.out.println();
					}
					if (tmp==null) continue;
					medicalRec.add(tmp);
//					System.out.println("got one " + tmp.getBizcode() + " " + tmp.getDoct_name());
//					qrService.completeTask(userId, tmp);
				}
			}
		}
		for(MedicalRecipel m:medicalRec){
			qrService.completeTask(userId, m);
		}
		return medicalRec.size();
	}
	
	public void test(String userId) {
		VOQueryLargeCost temp = new VOQueryLargeCost();
		//temp.set
		MedicalRecipel tmp = this.logiccostToMedicalRecipel(userId,temp,2);
		qrService.completeTask(userId, tmp);
	}
	
	public List <VOQueryLargeCost> getLogicCost (String bizcode, String time){
		String sql = dicService.getSqlByBizcode(bizcode);
		java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyy-MM-dd");
		if(time == null){
			sql = String.format(sql, format.format((new Date().getTime() - (long)24*60*60*1000)).toString());
		}
		else{
			sql = String.format(sql, time);
		}
		try {
			return super.getClassedAllList(sql, VOQueryLargeCost.class);
		} catch (DangerousOperatorException e) {
			e.printStackTrace();
		}
		return null;
	}
	

	
	public MedicalRecipel logiccostToMedicalRecipel(String userId,VOQueryLargeCost list,int type){
		MedicalRecipel mr = new MedicalRecipel();
		String Bizcode = qryPermissionService.getBizFlowConfig("recipel").getFullBizcode();
		String flowid = qryPermissionService.getBizFlowConfig("recipel").getFlowid();
		
		String typename []={"诊查费","床位收费天数","护理天数","吸氧天数","重症监护"};
		String typecode []={"182","181","178","183","184"};
		Date _date = list.getOUTHOSPITALAT();
		_date = _date !=null?DateUtil.addDate(_date, 1):new Date();
		mr.setInquiry_date(_date);
		mr.setCreateTime(_date);
		mr.setInquiry_item("逻辑异常");
		mr.setInquiry_item_sub(typename[type]);
		mr.setInquiry_item_subcode(typecode[type]);
		mr.setInquiry_item_code("177");
		//住院号
		mr.setZyhm(list.getZyhm());
		//科室名称
		mr.setDoct_depart_name(list.getDoct_depart_name());
		if (list.getDoct_depart_code()==null) return null;
		if (list.getDoct_depart_code().compareTo("114")==0) return null;
		mr.setDoct_depart_code(list.getDoct_depart_code());
		//记录编号
		mr.setPatient_type("2");
		mr.setPatient_id(list.getPatient_id().toString());
		mr.setPatient_name(list.getPatient_name());
		mr.setInhzospitalat(list.getINHZOSPITALAT());
		mr.setOuthospitalat(list.getOUTHOSPITALAT());
		if(list.getDoct_id() == null || list.getDoct_id() < 0){
			return null;
		}
		mr.setDoct_name(list.getDoct_name());
		mr.setDoct_id(list.getDoct_id().toString());
//		mr.setInquiry_date(list.getOUTHOSPITALAT().set);
		//mr.setPatient_id("3333");
		if (type==1||type==0){
			if (list.getHLTS()==null) return null;
			if (list.getZYTS()==null) return null;
			if (list.getHLTS()-list.getZYTS()>0){
				mr.setInquiry_reason(typename[type]+"异常，超出住院天数"+(list.getHLTS()-list.getZYTS())+"天");
			}
			else if (list.getHLTS()<=list.getZYTS()-2){
				mr.setInquiry_reason(typename[type]+"异常，小于住院天数"+(list.getZYTS()-list.getHLTS())+"天");
			}
			else return null;
		}
		else if (type==2) {
			if (list.getZZJHXS()==null) return null;
			if (list.getHLTS()==null) return null;
			if (list.getZYTS()==null) return null;
			Double ZZJHXS = list.getZZJHXS();
			Double temp = Math.ceil(ZZJHXS/24);
			Long ZZTS = temp.longValue();
			Long HLTS = list.getHLTS();
			Long ZYTS = list.getZYTS();
			if (HLTS+ZZTS>ZYTS){
				mr.setInquiry_reason(typename[type]+"异常，超出住院天数"+(HLTS+ZZTS-ZYTS)+"天");
			}
//			else if (HLTS+ZZTS<=ZYTS-2){
//				mr.setInquiry_reason(typename[type]+"异常，小于住院天数"+(ZYTS-HLTS+ZZTS)+"天");
//			}
			/**if (ZZJHXS>0){
				if (){
					
				}
			}**/
			else return null;
		}
		else if (type==3){
			String totalwrong="";
			String feewrong="";
			String dayswrong="";
			if (list.getXYZXS()==null) return null;
			if (list.getXYTS()==null) return null;
			if (list.getZYTS()==null) return null;
			Double hours=list.getXYZXS()-list.getXYTS()*24;
//			if (hours>0){
//				totalwrong="吸氧小时超出小时数总小时数"+hours.toString()+"小时,";
//			}
			if (list.getFYYC()==1){
				feewrong="吸氧总小时数异常，吸氧总小时数为"+list.getXYZXS().toString()+"小时,";
			}
			Long days=list.getXYTS()-list.getZYTS();
			if (days>0){
				dayswrong="吸氧天数大于住院天数"+days.toString()+"天";
			}
			if (dayswrong==""&&totalwrong==""&&feewrong=="") return null;
			mr.setInquiry_reason(typename[type]+"异常:"+totalwrong+feewrong+dayswrong);
			
			
		}
	
		//test用
		mr.setFlowid(flowid);
		mr.setFullBizcode(Bizcode);
		return mr;
	}
	
}
